package org.pr.ddddesigner.infrastructure.helper;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author chenbin
 */
public class ReflectHelper {
    private ReflectHelper() throws IllegalAccessException {
        throw new IllegalAccessException();
    }

    @SuppressWarnings("unchecked")
    public static <T> T getDeclaredFieldValue(Object obj, String fieldName) throws ReflectiveOperationException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        final boolean isInAccessible = !field.isAccessible();

        if (isInAccessible) {
            field.setAccessible(true);
        }
        try {
            return (T) field.get(obj);
        } finally {
            if (isInAccessible) {
                field.setAccessible(false);
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T invokeDeclaredMethod(Object obj, String methodName) throws ReflectiveOperationException {
        Method method = obj.getClass().getDeclaredMethod(methodName);
        final boolean isInAccessible = !method.isAccessible();

        if (isInAccessible) {
            method.setAccessible(true);
        }
        try {
            return (T) method.invoke(obj);
        } finally {
            if (isInAccessible) {
                method.setAccessible(false);
            }
        }
    }
}
